题目

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:

Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3 012 2
1 [3 -1 -3] 5 3 6 7 3 123 3
1 3 [-1 -3 5] 3 6 7 5 234 4
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

思路

解法1:max heap

a.维护一个大顶堆
b.取Max->top

复杂度O(n*logk)

解法2:双端队列

a.入队
b.维护

复杂度O(n*1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.ArrayDeque;
import java.util.Deque;

/*
* @lc app=leetcode id=239 lang=java
*
* [239] Sliding Window Maximum
*/
class Solution {
public static int[] maxSlidingWindow(int[] nums, int k) {
if (nums.length <= 0) {
return nums;
}

Deque<Integer> window = new ArrayDeque<>();// 用于储存窗口的下标
int[] res = new int[nums.length - k + 1];
// 从左边开始前进
for (int i = 0; i < nums.length; i++) {
//1.窗口界限 2.窗口左边最大的剔除

// 1
if (!window.isEmpty() && window.peek() <= i - k) {
window.pollFirst();
}


// 2
// 比窗口左边的小,继续,比窗口的大,删除左边的
while (!window.isEmpty() && nums[window.peekLast()] < nums[i]) {
window.pollLast();
}

window.offer(i);


System.out.println(window);
if (i >= k - 1) {
res[i - k + 1] = nums[window.peek()];
}

}

return res;

}
}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×